// import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router-dom';
import Button from '@kuiper-components/button';
import Dialog from '@kuiper-components/dialog';
import Helper from '../../Helper';
import {
	FREQ_UNIT_MAP,
	VUL_PATTERN,
	VUL_TYPE_MAP,
	SSL_CATEGORY_KEY_LABEL_MAP,
	INFORM_OPTIONS,
} from '../../../../common/constants';
import collectType from '../../../../common/collectType';
import s from './style.module.css';
import { useQuery, gql } from '@apollo/client';
import CollectFrequency from '../../CollectFrequency';
import Tooltip from '@kuiper-components/tooltip';
import { EyeOutlined } from '@ant-design/icons';

const ALERT_GROUP_QUERY = gql`
	{
		AlertGroupMany {
			isDefault
			receiverIds
			name
			_id
		}
	}
`;
const QUEYR_GQL = gql`
	{
		VulPluginId {
			id
			label
			taskType
			category
		}
	}
`;

function VulMonitorSetting({
	className,
	children,
	isLatestTask,
	host,
	triggerType,
	taskSettings,
	jobId,
	taskType,
	note,
	alertSettings,
}) {
	const [visible, setVisible] = React.useState(false);
	const [groupData, setGroupData] = React.useState([]);
	const { data } = useQuery(QUEYR_GQL);
	const { data: alertData } = useQuery(ALERT_GROUP_QUERY);
	const groupArr = [];
	const notigicationArr = [];
	const vulWarnIds = data?.VulPluginId || [];
	let vulLabel = '';
	alertSettings &&
		INFORM_OPTIONS.forEach(e => {
			alertSettings.notification[e.value] && notigicationArr.push(e.label);
		});
	if (triggerType === 'special') {
		for (let i = 0; i < vulWarnIds.length; i++) {
			if (taskSettings?.collect?.vul?.indexOf(vulWarnIds[i].id) > -1) {
				vulLabel = vulWarnIds[i].label;
				break;
			}
		}
	}
	const aletSettings = settings => {
		if (!settings) return '未开启';

		if (taskType === 'vul') {
			const vul = [].concat(settings?.collect?.vul || []);

			if (triggerType === 'manual' && vul[0]) {
				const vulArr = [];
				for (let i = 0; i < vulWarnIds.length; i++) {
					if (vul.length <= 0) {
						break;
					} else if (vul.indexOf(vulWarnIds[i].id) > -1) {
						vulArr.push(vulWarnIds[i].label);
						vul.splice(vul.indexOf(vulWarnIds[i].id), 1);
					}
				}
				if (vulArr.length > 1) {
					return (
						<>
							<span>
								{vulArr[0]} 等{vulArr.length}个漏洞{' '}
							</span>
							<Tooltip
								placement="top"
								overlay={<span className={s.tipSpan}>{vulArr.join('，')}</span>}
								overlayClassName={s.helpTooltip}
							>
								<EyeOutlined style={{ fontSize: '16px', color: '#08c' }} />
							</Tooltip>
						</>
					);
				} else {
					return <span>{vulArr[0]}漏洞</span>;
				}
			} else {
				const vulType = settings?.alert.vulType || [];
				const vulTypeArr = vulType.map(e => {
					return VUL_TYPE_MAP[e];
				});
				if (Object.keys(VUL_TYPE_MAP).length === vulType.length) {
					return (
						<>
							<span>所有类型漏洞 </span>
							{/* <Tooltip
								placement="top"
								overlay={
									<span>{vulTypeArr.join()}</span>
								}
								overlayClassName={s.helpTooltip}
							>
								<EyeOutlined />
							</Tooltip> */}
						</>
					);
				} else {
					return (
						<>
							<span>
								{vulType.length > 1
									? `${VUL_TYPE_MAP[vulType[0]]}等${vulType.length}类漏洞`
									: VUL_TYPE_MAP[vulType[0]]}
							</span>
							<Tooltip
								placement="top"
								overlay={
									<span className={s.tipSpan}>{vulTypeArr.join('，')}</span>
								}
								overlayClassName={s.helpTooltip}
							>
								<EyeOutlined style={{ fontSize: '16px', color: '#08c' }} />
							</Tooltip>
						</>
					);
				}
			}
		}

		const plugins = settings?.collect?.pluginCategories || [];

		return (
			<span>{plugins.map(p => SSL_CATEGORY_KEY_LABEL_MAP[p]).join(' ')}</span>
		);
	};
	React.useEffect(() => {
		if (alertSettings && alertData) {
			alertData.AlertGroupMany.forEach(e => {
				if (alertSettings.alertGroupIds.includes(e._id)) {
					groupArr.push(e.name);
				}
			});
		}
		setGroupData(groupArr);
	}, [alertData]);
	return (
		<>
			<Button
				link
				primary
				className={className}
				onClick={() => setVisible(true)}
			>
				{children}
			</Button>
			<Dialog
				title={
					<div className={s.dialogtitle}>
						<span>{children}</span>
						<Helper
							overlayClassName={s.helpTooltip}
							overlay={
								<>
									<p>以下配置为该资产当次任务检测时设置的参数。</p>
									<p>
										如需查看最新周期性参数配置，请前往“资产列表-管理-周期配置”
									</p>
								</>
							}
							placement="right"
						/>
					</div>
				}
				visible={visible}
				className={s.modal}
				onClose={() => setVisible(false)}
			>
				<table>
					<tbody>
						<tr>
							<td className={s.field}>资产名称：</td>
							<td className={s.value}>{note}</td>
						</tr>
						<tr>
							<td className={s.field}>资产地址：</td>
							<td className={s.value}>
								<div title={host} className={s.target}>
									{host}
								</div>
							</td>
						</tr>
						<tr>
							<td className={s.field}>监测方式：</td>
							<td className={s.value}>
								<span>
									{collectType({
										taskType,
										triggerType,
										collect: taskSettings?.collect,
									}) || <span className={s.nullspan}>--</span>}
								</span>
							</td>
						</tr>
						{triggerType !== 'special' && (
							<>
								<tr>
									<td className={s.field}>监测内容：</td>
									<td className={s.value}>
										<span>{aletSettings(taskSettings)}</span>
									</td>
								</tr>
								{triggerType !== 'manual' && (
									<tr>
										<td className={s.field}>监测频率：</td>
										<td className={s.value}>
											<CollectFrequency
												viewmode
												value={taskSettings?.interval}
												unitMap={FREQ_UNIT_MAP}
											/>
										</td>
									</tr>
								)}

								{taskType === 'vul' && (
									<>
										{taskSettings?.collect?.speed && (
											<tr>
												<td className={s.field}>监测模式：</td>
												<td className={s.value}>
													<span>
														{VUL_PATTERN[taskSettings?.collect?.speed]}
													</span>
												</td>
											</tr>
										)}
										{taskSettings?.collect?.depth && (
											<tr>
												<td className={s.field}>监测深度：</td>
												<td className={s.value}>
													<span className={s.hl}>
														{taskSettings?.collect?.depth}
													</span>
													层
												</td>
											</tr>
										)}

										{taskSettings?.collect?.maxPage && (
											<tr>
												<td className={s.field}>监测最大URL数：</td>
												<td className={s.value}>
													<span className={s.hl}>
														{taskSettings?.collect?.maxPage}
													</span>
													页
												</td>
											</tr>
										)}
									</>
								)}
							</>
						)}
						{triggerType === 'special' && (
							<tr>
								<td className={s.field}>监测内容：</td>
								<td className={s.value}>{vulLabel}</td>
							</tr>
						)}
						{alertSettings && (
							<>
								<tr>
									<td className={s.field}>通知对象：</td>
									<td className={s.value}>
										{groupData[0]
											? groupData.map(e => {
													return (
														<span className={s.hl2} key={e}>
															{e}
														</span>
													);
											  })
											: '--'}
									</td>
								</tr>
								<tr>
									<td className={s.field}>通知类型：</td>
									<td className={s.value}>
										{notigicationArr[0]
											? notigicationArr.map((e, i) => {
													return (
														<span key={e}>
															{e}
															{i === notigicationArr.length - 1 ? '' : '、'}
														</span>
													);
											  })
											: '--'}
									</td>
								</tr>
							</>
						)}
					</tbody>
				</table>
				<div className={s.actions}>
					{jobId &&
						isLatestTask &&
						(triggerType === 'schedule' ||
							triggerType === 'scheduleIncrement') && (
							<Link
								to={`/job/${jobId}/weakness/${taskType}`}
								className={s.link}
							>
								<Button className={s.actionBtn}>前往修改</Button>
							</Link>
						)}

					<Button
						primary
						className={s.actionBtn}
						onClick={() => setVisible(false)}
					>
						取消
					</Button>
				</div>
			</Dialog>
		</>
	);
}

VulMonitorSetting.propTypes = {
	className: PropTypes.string,
	children: PropTypes.node,
	host: PropTypes.string.isRequired,
	triggerType: PropTypes.string.isRequired,
	taskSettings: PropTypes.shape({
		collect: PropTypes.object.isRequired,
		interval: PropTypes.number,
		alert: PropTypes.object,
		enable: PropTypes.bool,
	}),
	jobId: PropTypes.string,
	taskType: PropTypes.string,
	isLatestTask: PropTypes.bool,
	note: PropTypes.string,
	alertSettings: PropTypes.any,
};
VulMonitorSetting.defaultProps = {
	className: '',
	note: '',
};

export default VulMonitorSetting;
